// pages/myself/bulletin-board/bulletinBoard.js
import * as echarts from '../../components/ec-canvas/echarts'
import WxCountUp from '../../utils/WxCountUp.js'
let audioCtx = null
const app = getApp()
let barChart = null
let option = {
  radar: {
    center: ['50%', '52%'],
    radius: 84,
    name: {
      color: '#555555',
      fontSize: 13,
      formatter: function (value) {
        return value
      }
    },
    splitArea: {
      areaStyle: {
          color: [ '#FFFFFF', '#fbfdff', ].reverse(),
      }
    },
    nameGap: '12',
    indicator: [{name: '场景完整度', max: 100}, {name: '知识准确度', max: 100}, {name: '服务表现力', max: 100}, {name: '场景熟练度', max: 100}, {name: '服务应变力', max: 100}],
    splitArea: {
      show: false,
      areaStyle: {
      }
    },
    axisLine: {
      lineStyle: {
        width: 1,
        color: '#f1f2f3'
      }
    },
    splitLine: {
      lineStyle: {
        width: 1,
        color: '#f1f2f3'
      }
    }
  },
  series: [{
    name: '区域分布',
    type: 'radar',
    symbol: 'circle', // 拐点的样式，还可以取值'rect','angle'等
    symbolSize: 8, // 拐点的大小
    symbol: "none",
    areaStyle: {
      normal: {
        color: '#0099F7'
      }
    },
    itemStyle: {
      color: "#fff",
      borderColor: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
          offset: 0,
          color: '#0061E3'
      }, {
          offset: 1,
          color: '#0061E3'
      }], false),
      borderWidth: 4,
      opacity: 1
  },
    lineStyle: {
      color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
          offset: 0,
          color: '#0061E3'
      }, {
          offset: 1,
          color: '#0061E3'
      }], false),
      width: 3
  },
    data: [{
      value: [],
      name: '',
      contentList: []
    }]
  }]
}
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    practiceIds: {
      type: Array,
      observer (practiceIds) {
        practiceIds.length > 0 && this.getScore()
      }
    }
  },

  /**
   * 组件的初始数据
   */
  options: {
    addGlobalClass: true
  },
  data: {
    cache_totalTime:0,
    timer:null,
    playing:false,
    audioSrc:'',
    audioTime:'00:00:00',
    totalTime:'00:00:00',
    score: 0,
    show: false,
    guideList: [],
    tip: '',
    cdnPath: app.globalData.CDNPATH,
    ecComprehensive: {
      onInit: function (canvas, width, height, dpr) {
        barChart = echarts.init(canvas, null, {
          width: width,
          height: height,
          devicePixelRatio: dpr // new
        });
        canvas.setChart(barChart);
        barChart.setOption(option);
        return barChart;
      }
    }
  },
  onShow () {
  },

  /**
   * 组件的方法列表
   */
  created: function () {
    if (this.data.practiceIds.length > 0) {
      this.getScore()
    }
    this.getRadarMapDesc()
    audioCtx = wx.createInnerAudioContext()
  },
  detached () {
    this.data.timer && clearInterval(this.data.timer)
    audioCtx && audioCtx.stop()
  },
  methods: {
    timeCalc() {
      let hour = 0
      let minute = 0
      let second = 0
      let cache_time = 0
      this.data.timer && clearInterval(this.data.timer)
      this.data.timer = setInterval(() => {
        cache_time++
        if(cache_time > this.data.cache_totalTime){
          this.data.timer && clearInterval(this.data.timer)
          return false
        }
        if (second >= 0) {
          second++
        }
        if (second >= 60) {
          second = 0
          minute++
        }
        if (minute >= 60) {
          minute = 0
          hour++
        }
        const time =
          (hour > 9 ? hour : '0' + hour) +
          ':' +
          (minute > 9 ? minute : '0' + minute) +
          ':' +
          (second > 9 ? second : '0' + second)
         this.setData({
          audioTime:time
         }) 
      }, 1000)
    },
    getAudioCtx () {
      audioCtx.src = this.data.audioSrc
      audioCtx.onCanplay(()=> {
        // 必须。不然也获取不到时长
        audioCtx.duration
        setTimeout(() => {
          const duration = audioCtx.duration
          const cache_second = parseInt(duration)
          console.log(duration,'duration====================')
          this.setData({
            totalTime: this.secondToTime(duration*1000),
            cache_totalTime:cache_second
          })
        }, 200)
      }) 
      audioCtx.onEnded(()=>{
        this.data.timer && clearInterval(this.data.timer)
        this.setData({
          playing:false,
          audioTime:'00:00:00',
          timeShow:false
        })
      })
    },
    secondToTime(duration) {
      let seconds = parseInt((duration / 1000) % 60)
      let minutes = parseInt((duration / 1000 / 60) % 60)
      let hours = parseInt((duration / (1000 * 60 * 60)) % 24)
      hours = (hours < 10) ? '0' + hours : hours
      minutes = (minutes < 10) ? '0' + minutes : minutes
      seconds = (seconds < 10) ? '0' + seconds : seconds
      return hours + ':' + minutes + ':' + seconds
    },
    audioPlay () {
      audioCtx.play()
      this.timeCalc()
      this.setData({
        playing:true,
        timeShow:true
      })
    },
    audioPause () {
      audioCtx.stop()
      this.setData({
        playing:false,
        audioTime:'00:00:00',
        timeShow:false
      })
      this.data.timer && clearInterval(this.data.timer)
    },
    getRadarMapDesc () {
      let mapkey = {
        'scene_integrity': '场景完整度',
        'service_resilience': '服务应变力',
        'scene_proficiency': '场景熟练度',
        'service_performance': '服务表现力',
        'knowledge_accuracy': '知识准确度',
        'speed': '语速',
        'keyword': '关键词缺少个数',
        'matching_rate': '匹配度系数',
        'forbidden_word': '违禁词个数'
      }
      app.api.post({
        url: 'descConfig_getBizDescConfigs',
        data: { descType: 'radar_map_desc' }
      }).then(res => {
        res.map((v, k) => {
          v.content = `${mapkey[v.descSubtype]}：${v.descContent}`
        })
        this.setData({
          contentList: res
        })
        console.log(res)
      })
    },
    close () {
      this.data.show = !this.data.show
      this.setData({
        show: this.data.show
      })
    },
    getGuide (res) {
      let params = {
        knowledgeAccuracy: res.knowledgeAccuracyScore,
        practiceRecordId: this.data.practiceIds[0],
        sceneIntegrity: res.sceneCompletionScore,
        sceneProficiency: res.sceneProficiencyScore,
        servicePerformance: res.servicePerformanceScore,
        serviceResilience: res.serviceResilienceScore
      }
      app.api.post({
        url: 'bizGuidanceAdvise_getGuidanceAdviseContent',
        data: params
      }).then(res => {
        this.setData({
          guideList: res ? res : []
        })
      })
    },
    getScore () {
      const { practiceIds } = this.data
      console.log(practiceIds, '开始查询', new Date())
      app.api.post({
        url: 'get_practice_score',
        data: practiceIds
      }).then(res => {
        console.log(res, '查询结束', new Date())
        this.setData({
          score: res.score ? res.score : 0,
          tip: res.tip ? res.tip : '',
          audioSrc:res.practiceAudioResList[0].audioUrl
        })
        this.getAudioCtx()
        this.getGuide(res.evaluationResp)
        let score = this.data.score
        var x = String(score).indexOf('.') + 1;   //小数点的位置
        var y = String(score).length - x;  //小数的位数
        console.log(x === 0, y)
        if(x === 0){
          this.countUp = new WxCountUp('score', score, {}, this);
        } else {
          this.countUp = new WxCountUp('score', score, {decimalPlaces: y}, this)
        }
        this.countUp.start(() => console.log('Complete!'))
        this.triggerEvent('scoreChange', {score: res.examResult}, {})
        console.log(res.evaluationResp, option.radar.indicator)
        option.radar.indicator[1].max = res.evaluationResp.maxKnowledgeAccuracyScore
        let chartDate = [res.evaluationResp.sceneCompletionScore, res.evaluationResp.knowledgeAccuracyScore, res.evaluationResp.servicePerformanceScore, res.evaluationResp.sceneProficiencyScore, res.evaluationResp.serviceResilienceScore]
        option.series[0].data[0].value = chartDate
        if (barChart) {
          barChart.clear()
          barChart.setOption(option, true)
        }
      })
    }
  }
})